import java.util.concurrent.TimeUnit;

/**
 * @author wcj
 * @Date 2021/6/8 11:16
 * @Version 1.0
 */
public class ShutDown {

    /**
     * 通过中断和设置一个boolean类型开关去安全的终止线程
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runner(), "One");
        thread.setDaemon(true);
        thread.start();
        TimeUnit.MILLISECONDS.sleep(100);
        thread.interrupt();

        Runner two = new Runner();
        Thread thread1 = new Thread(two, "Two");
        thread1.setDaemon(true);
        thread1.start();
        TimeUnit.MILLISECONDS.sleep(100);
        two.cancel();
    }


    static class Runner implements Runnable {
        private long i;
        private volatile boolean on = true;

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                i++;
            }
        }

        public void cancel() {
            this.on = false;
        }
    }
}
